var app = angular.module('app');

/**
 * 解决div输入无法使用ng-model指令
 */
app.directive('contenteditable', ['$sce', function($sce) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function($scope, element, iAttrs, ctrl) {
            element.bind('input', function() {
                $scope.$apply(function() {
                    ctrl.$setViewValue(element.text());
                });
            });
            ctrl.$render = function() {
                element.text(ctrl.$viewValue);
            };
        }
    };
}]);

app.directive('lmEditor', ['$timeout', 'Storage', 'FileSystem', 'Nw', function($timeout, Storage, FileSystem, Nw) {
    return {
        restrict: 'A', // E = Element, A = Attribute, C = Class, M = Comment
        link: function($scope, iElm, iAttrs, controller) {
            // var userConfig = storage.get('user-config');
            //解析器配置
            var options = {
                renderer: new marked.Renderer(),
                gfm: true,
                // tables: true,
                // breaks: true,
                // pedantic: true,
                sanitize: true,
                // smartLists: true,
                // smartypants: true
            };

            //监听输入
            $scope.$watch('markcontent', function(newval, oldval, scope) {
                if (!newval) newval = '';
                //这儿输入可能是纯数字，必须转换成字符串才能有replace等String类型的方法
                scope.htmlcontent = marked(String(newval));
            });

            //写入文件
            // function flush() {
            //     FileSystem.write($scope.state.dir, $scope.state.file.name, $scope.markcontent);
            // }

            //定时写入内容，30秒自动保存一次
            // $timeout(flush, 1000 * 30);

            iElm.bind('keydown', 'ctrl+s', function(event) {
                //判断是否存在存储路径
                if (!$scope.savePath) {
                    angular.element('#saveas').click().unbind('change').change(function(event) {
                        console.log(event);
                        var path = $scope.savePath = event.target.value;
                        FileSystem.write(path, $scope.markcontent);
                    });
                } else {
                    FileSystem.write($scope.savePath, $scope.markcontent);
                }
            });

            iElm.on('dragenter dragover dragleave', function(event) {
                event.stopPropagation();
                event.preventDefault();
            });

            iElm[0].addEventListener("drop", function(event) {
                event.stopPropagation();
                event.preventDefault();
                if (event.dataTransfer.files.length > 0) {
                    var path = event.dataTransfer.files[0].path;
                    var markcontent = FileSystem.read(path);
                    $timeout(function() {
                        $scope.markcontent = markcontent;
                        $scope.savePath = path;
                    });
                }
            }, false);


        }
    };
}]);

app.directive('lmTools', ['$timeout', 'Nw', function($timeout, Nw) {
    // Runs during compile
    return {
        // name: '',
        // priority: 1,
        // terminal: true,
        // scope: {}, // {} = isolate, true = child, false/undefined = no change
        // controller: function($scope, $element, $attrs, $transclude) {},
        // require: 'ngModel', // Array = multiple requires, ? = optional, ^ = check parent elements
        // restrict: 'A', // E = Element, A = Attribute, C = Class, M = Comment
        // template: '',
        // templateUrl: '',
        // replace: true,
        // transclude: true,
        // compile: function(tElement, tAttrs, function transclude(function(scope, cloneLinkingFn){ return function linking(scope, elm, attrs){}})),
        link: function($scope, iElm, iAttrs, controller) {
            $scope.isFullscreen = false;
            $scope.enterFullscreen = function() {
                Nw.Window.enterFullscreen();
                $scope.isFullscreen = !$scope.isFullscreen;
            };
            $scope.leaveFullscreen = function() {
                Nw.Window.leaveFullscreen();
                $scope.isFullscreen = !$scope.isFullscreen;
            };

            angular.element(document).bind('keydown', 'esc', function(event) {
                Nw.Window.leaveFullscreen();
                $timeout(function() {
                    $scope.isFullscreen = false;
                })
            });
        }
    };
}]);

app.directive('lmSlimscroll', [function() {
    return {
        link: function($scope, iElm, iAttrs, controller) {
            iElm.slimscroll({
                height: 'auto',
            });
        }
    };
}]);

// app.directive('lmSidebar', ['$compile', '$rootScope', '$timeout', 'FileSystem', function($compile, $rootScope, $timeout, FileSystem) {
//     // Runs during compile
//     return {
//         restrict: 'A', // E = Element, A = Attribute, C = Class, M = Comment
//         link: function($scope, iElm, iAttrs, controller) {
//             $scope.open = false;
//             //编译遮罩层
//             var backdrop = $compile('<div class="modal-backdrop" ng-if="open" ng-click="toggleFolder()" id="open-folder-backdrop"></div>')($scope);
//             angular.element('body').append(backdrop);
//             //遮罩与文件夹的显示与隐藏
//             $scope.toggleFolder = function() {
//                 $scope.open = !$scope.open;
//                 angular.element('#open-folder-backdrop').toggleClass('fade in').toggle();
//             };

//             //获取文件列表
//             FileSystem.files($scope.state.dir).then(function(files) {
//                 var fileobjs = [];
//                 for (var i = 0; i < files.length; i++) {
//                     fileobjs[i] = { name: files[i], real: true };
//                 }
//                 $scope.files = fileobjs;
//             });
//             //新建文件逻辑
//             $scope.newfile = function() {

//             };
//         }
//     };
// }]);


// app.directive('lmSelection', ['$timeout', function($timeout) {
//     return {
//         link: function($scope, iElm, iAttrs, controller) {
//             if (iAttrs.lmSelection === "true") {
//                 $timeout(function() {
//                     iElm.focus().select();
//                 });
//             }
//         }
//     };
// }]);

// app.directive('lmFolder', ['$timeout', 'Nw', 'Folder', 'Storage', function($timeout, Nw, Folder, Storage) {
//     // Runs during compile
//     return {
//         link: function($scope, iElm, iAttrs, controller) {
//             $scope.folders = Folder.list();
//             $scope.current = Folder.current();
//             $scope.addFolder = function(fileinput) {
//                 angular.element(fileinput).click().unbind('change').change(function(event) {
//                     $timeout(function() {
//                         var folder = {
//                             // name: Nw.Path.basename(event.target.value),
//                             path: event.target.value
//                         };
//                         $scope.folders = Folder.add(folder);

//                         $scope.current = Folder.current($scope.folders.length - 1);
//                     });
//                 });
//             }

//             $scope.delFolder = function() {
//                 $scope.folders = Folder.del($scope.current);
//             }

//             $scope.active = function(index) {
//                 $scope.current = Folder.current(index);
//             };
//         }
//     };
// }]);

// app.directive('lmArticle', ['FileSystem', function(FileSystem) {
//     // Runs during compile
//     return {
//         link: function($scope, iElm, iAttrs, controller) {
//             //监控当前目录的变化进行获取对应文档列表
//             $scope.$watch('current', function(newval, oldval, scope) {
//                 console.log('current');
//                 $scope.files = FileSystem.files($scope.folders[$scope.current].path);
//                 console.log($scope.files);
//             });
//         }
//     };
// }]);
